package com.ctgu.computer.interceptor;

import com.ctgu.computer.common.UserLocalTread;
import com.ctgu.computer.prop.JwtProperties;
import com.ctgu.computer.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;
    private static String USER = "userId";
    private static String ADMIN = "adminId";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        String token =request.getHeader("token");
        try {
            log.info("jwt校验:{}",token);
            Claims claims = JwtUtils.parseJwt(token, jwtProperties.getSignKey());
            if(claims.get(USER)!=null){
                Integer userId = Integer.valueOf(claims.get(USER).toString());
                log.info("当前为普通用户,id:{}",userId);
                UserLocalTread.setUserId(userId);
            }
            if(claims.get(ADMIN)!=null){
                Integer adminId = Integer.valueOf(claims.get(ADMIN).toString());
                log.info("当前为管理员,id:{}",adminId);
                UserLocalTread.setAdminId(adminId);
            }
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }
}
